package models

import (
	"errors"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

//品牌
type ErpBrand struct {
	Id           int64
	DepartmentId int64
	BrandName    string
	Pinyin       string
	Status       int
	Summary      string
	CreatedAt    int64
	UpdatedAt    int64
}

//查询
type ErpBrandQueryParam struct {
	BaseQueryParam
	Filter       string
	DepartmentId int64
}

func (a *ErpBrand) TableName() string {
	return ErpBrandTableName()
}

func ErpBrandTableName() string {
	return TableName("erp_brand")
}

func GetErpBrandById(id int64) (*ErpBrand, error) {

	r := new(ErpBrand)
	err := orm.NewOrm().QueryTable(ErpBrandTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func ErpBrandList(params *ErpBrandQueryParam) []*ErpBrand {

	ls := make([]*ErpBrand, 0)
	query := orm.NewOrm().QueryTable(ErpBrandTableName())

	sortorder := "-Id"

	query = query.Filter("status", 1)
	query = query.Filter("DepartmentId", params.DepartmentId)
	query.OrderBy(sortorder).All(&ls)

	return ls
}

func ErpBrandPageList(params *ErpBrandQueryParam) ([]*ErpBrand, int64) {

	ls := make([]*ErpBrand, 0)

	query := orm.NewOrm().QueryTable(ErpBrandTableName())

	if len(params.Filter) > 0 {
		query = query.Filter("brand_name__istartswith", params.Filter)
	}
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	query = query.Filter("DepartmentId", params.DepartmentId)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func ErpBrandAdd(c *ErpBrand) (int64, error) {

	c.Status = 1
	c.Pinyin = utils.ConvertPinyin(c.BrandName)
	c.UpdatedAt = time.Now().Unix()
	c.CreatedAt = time.Now().Unix()

	return orm.NewOrm().Insert(c)
}

func (a *ErpBrand) ErpBrandEdit(filter ...string) error {

	a.Pinyin = utils.ConvertPinyin(a.BrandName)
	a.UpdatedAt = time.Now().Unix()

	if _, err := orm.NewOrm().Update(a, filter...); err != nil {
		return err
	}
	return nil
}

func ErpBrandDel(id, depid int64) error {

	var c ErpBrand
	c = ErpBrand{Id: id, Status: 2}
	orm.NewOrm().Read(&c)
	if c.Status == 1 {
		c.Status = 2
	} else {
		c.Status = 1
	}
	if c.DepartmentId != depid {
		return errors.New("数据不存在")
	}
	if _, err := orm.NewOrm().Update(&c, "status"); err != nil {
		return err
	}
	return nil
}
